#!/usr/bin/env python
# -*- coding: utf-8 -*-
import redis
from logger import logger


class RedisHelper:
    def __init__(self):
        if not hasattr(RedisHelper, 'pool'):
            # 创建redis连接pool
            RedisHelper.pool = redis.ConnectionPool(redis.Connection, host="r-uf61x52g8b0cketmk7.redis.rds.aliyuncs.com",
                                        password="Cloudhis1234", port="6379", db=61, max_connections=None,
                                        decode_responses=True)
            print("redis init success")
        self.rdb = redis.Redis(connection_pool=RedisHelper.pool)

    # @staticmethod
    # def getRedisCoon():
    #     RedisHelper.pool = redis.ConnectionPool(redis.Connection, host="localhost",
    #                                             password="123456", port="6379", db=61, max_connections=None,
    #                                             decode_responses=True)

    def __del__(self):
        self.rdb.connection_pool.disconnect()

    def delete_by_key(self, key):
        self.rdb.delete(key)

    def get_by_key(self, key):
        return self.rdb.get(key)

    def set_by_key(self, key: str, value: str, expire_time):
        """
        :param key:
        :param value:
        :param expire_time:  毫秒
        :return:
        """
        result = self.rdb.set(key, value, px=expire_time)
        logger.info("set key:{} value:{} expire_time:{}".format(key, value, expire_time))
        return result

    def set_list_by_key(self, key, *value, push_type=0):
        if push_type == 0:
            self.rdb.lpush(key, *value)
        elif push_type == 1:
            self.rdb.rpush(key, *value)
        logger.info("set_list_by_key key:{} value:{} pushType:{}".format(key, value, push_type))

    def get_list_by_range(self, key, start=0, end=-1):
        return self.rdb.lrange(key, start, end)

    def get_list_by_index(self, key, index):
        return self.rdb.lindex(key, index)

    def pop_list_by_type(self, key, push_type=0):
        if push_type == 0:
            return self.rdb.lpop(key)
        elif push_type == 1:
            return self.rdb.rpop(key)
